<?php

namespace addon\lian\model\sqlmodel;

use think\Model;
use think\facade\Db;


class LianPubLineModel extends Model
{
    protected $name = 'lian_publine';

    protected $pk = 'id';


    public function member(){
        return $this->hasOne(MemberModel::class, 'member_id', 'member_id');
    }

    public function pidMember(){
        return $this->hasOne(MemberModel::class, 'member_id', 'pid');
    }

    public function upPidMember(){
        return $this->hasOne(MemberModel::class, 'member_id', 'up_pid');
    }


    /**
     * 获取公排下级会员
     * @param int $member_id 会员ID
     * @param int $deeplevel 当前深度
     * @param array $leveldata 层级数据
     * @return array
     */
    public function getPublineChildren($member_id, $deeplevel, $leveldata)
    {
        $deeplevel++;

        // 限制最大深度为10层
        if ($deeplevel > 10) {
            return [];
        }

        try {
            // 查询下级会员
            $list = $this->where('up_pid', $member_id)
                ->where('status', 0) // 只查询正常状态的会员
                ->order('position asc, create_time asc')
                ->select()
                ->toArray();

            $children = [];

            foreach ($list as $item) {
                // 获取会员信息
                $memberInfo = Db::name('member')
                    ->where('member_id', $item['member_id'])
                    ->field('nickname, headimg')
                    ->find();

                // 统一数据格式
                $childData = [
                    'member_id' => (int)$item['member_id'],
                    'pid' => (int)$item['pid'],
                    'up_pid' => (int)$item['up_pid'],  
                    'level' => (int)$item['level'],
                    'position' => (int)$item['position'],
                    'team_count' => (int)($item['team_count'] ?? 0),
                    'direct_count' => (int)($item['direct_count'] ?? 0),
                    'nickname' => $memberInfo['nickname'] ?? '未知会员',
                    'headimg' => $memberInfo['headimg'] ?: '/static/img/touxiang.png',
                ];

                // 构建显示名称
                if ($childData['pid'] == 0) {
                    $childData['name'] = $childData['nickname'] . '(ID:' . $childData['member_id'] . ',根节点)';
                } else {
                    $childData['name'] = $childData['nickname'] . '(ID:' . $childData['member_id'] . ',推荐人:' . $childData['pid'] . ')';
                }

                // 递归获取下级
                $childData['children'] = $this->getPublineChildren($childData['member_id'], $deeplevel, $leveldata);

                $children[] = $childData;
            }

            return $children;
        } catch (\Exception $e) {
            error_log('getPublineChildren Error: ' . $e->getMessage());
            return [];
        }
    }

}